// pages/admin-users/admin-users.js
const { apiService } = require('../../utils/api')
const { showSuccess, showError, showLoading, hideLoading } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    users: [],
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10,
    searchKeyword: '',
    statusFilter: -1, // -1: 全部, 0: 禁用, 1: 正常
    statusOptions: [
      { value: -1, label: '全部状态' },
      { value: 0, label: '禁用' },
      { value: 1, label: '正常' }
    ],
    showUserDetail: false,
    currentUser: null,
    totalUsers: 0,
    todayUsers: 0,
    activeUsers: 0,
    statsLoading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadUsersStats()
    this.loadUsers()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadUsers()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshUsers()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMoreUsers()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '用户管理',
      path: '/pages/admin-users/admin-users'
    }
  },

  /**
   * 加载用户统计数据
   */
  loadUsersStats: function() {
    this.setData({ statsLoading: true })

    apiService.getUsersStats()
      .then((stats) => {
        this.setData({
          totalUsers: stats.total || 0,
          todayUsers: stats.today || 0,
          activeUsers: stats.active || 0,
          statsLoading: false
        })
      })
      .catch((error) => {
        console.error('加载用户统计失败:', error)
        this.setData({ statsLoading: false })
      })
  },

  /**
   * 加载用户列表
   */
  loadUsers: function() {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      keyword: this.data.searchKeyword,
      status: this.data.statusFilter === -1 ? null : this.data.statusFilter
    }

    apiService.getUsersList(params)
      .then((result) => {
        const newUsers = result.list || []
        const users = this.data.pageNum === 1 ? newUsers : [...this.data.users, ...newUsers]

        this.setData({
          users: users,
          hasMore: newUsers.length === this.data.pageSize,
          loading: false
        })
      })
      .catch((error) => {
        this.setData({ loading: false })
        showError(error.message || '加载用户列表失败')
      })
  },

  /**
   * 刷新用户列表
   */
  refreshUsers: function() {
    this.setData({
      users: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadUsers()
    this.loadUsersStats()
  },

  /**
   * 加载更多用户
   */
  loadMoreUsers: function() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({
      pageNum: this.data.pageNum + 1
    })
    this.loadUsers()
  },

  /**
   * 搜索输入处理
   */
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  /**
   * 执行搜索
   */
  onSearch: function() {
    this.refreshUsers()
  },

  /**
   * 清空搜索
   */
  onClearSearch: function() {
    this.setData({
      searchKeyword: ''
    })
    this.refreshUsers()
  },

  /**
   * 状态筛选变化
   */
  onStatusFilterChange: function(e) {
    const value = parseInt(e.detail.value)
    this.setData({
      statusFilter: value
    })
    this.refreshUsers()
  },

  /**
   * 显示用户详情
   */
  showUserDetail: function(e) {
    const userId = e.currentTarget.dataset.id
    const user = this.data.users.find(u => u.id === userId)

    if (user) {
      this.setData({
        showUserDetail: true,
        currentUser: user
      })
    }
  },

  /**
   * 隐藏用户详情
   */
  hideUserDetail: function() {
    this.setData({
      showUserDetail: false,
      currentUser: null
    })
  },

  /**
   * 禁用用户
   */
  disableUser: function(e) {
    const userId = e.currentTarget.dataset.id
    const user = this.data.users.find(u => u.id === userId)

    if (!user) return

    wx.showModal({
      title: '确认禁用',
      content: `确定要禁用用户"${user.nickname || user.username}"吗？`,
      success: (res) => {
        if (res.confirm) {
          showLoading('禁用中...')

          apiService.disableUser(userId)
            .then(() => {
              hideLoading()
              showSuccess('用户禁用成功')
              this.refreshUsers()
            })
            .catch((error) => {
              hideLoading()
              showError(error.message || '禁用用户失败')
            })
        }
      }
    })
  },

  /**
   * 启用用户
   */
  enableUser: function(e) {
    const userId = e.currentTarget.dataset.id
    const user = this.data.users.find(u => u.id === userId)

    if (!user) return

    showLoading('启用中...')

    apiService.enableUser(userId)
      .then(() => {
        hideLoading()
        showSuccess('用户启用成功')
        this.refreshUsers()
      })
      .catch((error) => {
        hideLoading()
        showError(error.message || '启用用户失败')
      })
  },

  /**
   * 获取状态文本
   */
  getStatusText: function(status) {
    const statusMap = {
      0: '禁用',
      1: '正常'
    }
    return statusMap[status] || '未知'
  },

  /**
   * 获取状态样式类
   */
  getStatusClass: function(status) {
    const classMap = {
      0: 'status-disabled',
      1: 'status-normal'
    }
    return classMap[status] || ''
  },

  /**
   * 获取用户类型文本
   */
  getUserTypeText: function(userType) {
    const typeMap = {
      0: '普通用户',
      1: '管理员'
    }
    return typeMap[userType] || '未知'
  },

  /**
   * 格式化注册时间
   */
  formatRegisterTime: function(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
      return '今天'
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else if (days < 30) {
      return `${Math.floor(days / 7)}周前`
    } else {
      return date.toLocaleDateString()
    }
  },

  /**
   * 格式化最后登录时间
   */
  formatLastLoginTime: function(timestamp) {
    if (!timestamp) return '从未登录'
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 1) {
      return '刚刚'
    } else if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return date.toLocaleDateString()
    }
  }
})

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})